import BaseBarChartComponent from "./base-bar-chart.js";
// 精确复现样例的带右侧标签负值柱状图组件
class ExactNegativeBarChart extends BaseBarChartComponent {
    // 重写观察的属性列表
    static get observedAttributes() {
        const parentAttributes = super.observedAttributes;
        return [
            ...parentAttributes,
            'series-negative_colorpicker',    // 负值柱形颜色
            'series-positive_colorpicker',    // 正值柱形颜色
            'series-show-labels_radio'        // 是否显示标签
        ];
    }

    // 重写默认配置，完全匹配样例
    getDefaultConfig() {
        const parentConfig = super.getDefaultConfig();

        // 核心配置完全匹配样例
        parentConfig.titleAttrs = [
            ...parentConfig.titleAttrs,
            ['title-text_text', 'Bar Chart with Negative Value'],
            ['title-show_radio', true],
            ['title-left_slider', 'center'],
            ['title-top_slider', '0']
        ];

        parentConfig.gridAttrs = [
            ...parentConfig.gridAttrs,
            ['grid-top_slider', '80'],
            ['grid-bottom_slider', '30'],
            ['grid-lef_slidert', '5%'],
            ['grid-right_slider', '15%'],
            ['grid-containlabel_radio', true]
        ];

        parentConfig.xAxisAttrs = [
            ...parentConfig.xAxisAttrs,
            ['xaxis-type_select', 'value'],
            ['xaxis-position_text', 'top'],
            ['xaxis-splitline-show_radio', true],
            ['xaxis-splitline-linestyle-type_select', 'dashed']
        ];

        parentConfig.yAxisAttrs = [
            ...parentConfig.yAxisAttrs,
            ['yaxis-type_select', 'category'],
            ['yaxis-axisline-show_radio', false],
            ['yaxis-axistick-show_radio', false],
            ['yaxis-splitline-show_radio', false],
            ['yaxis-axislabel-show_radio', false],
            ['yaxis-data_array', JSON.stringify([
                'ten', 'nine', 'eight', 'seven', 'six',
                'five', 'four', 'three', 'two', 'one'
            ])]
        ];

        parentConfig.seriesAttrs = [
            ...parentConfig.seriesAttrs,
            ['series-name_text', 'Cost'],
            ['series-type_select', 'bar'],
            ['series-stack_text', 'Total'],
            ['negative-color', '#f56c6c'],
            ['positive-color', '#409eff'],
            ['show-labels', true]
        ];

        return parentConfig;
    }

    // 重写生成系列配置，精确匹配样例数据结构
    generateSeries(demoData, seriesConfig) {
        // 定义右侧标签配置
        const labelRight = {
            position: 'right'
        };

        // 返回的 series 数组
        const seriesList = [];

        // 遍历每个分组
        demoData.forEach(groupObj => {
            // groupObj 示例：{ "测试": [ { name, value }, ... ] }
            const groupName = Object.keys(groupObj)[0];  // 获取分组名，如 "测试"
            const items = groupObj[groupName];           // 获取该组的数据数组

            // 构建符合 echarts 要求的 data 数组
            const seriesData = items.map(item => {
                const valueItem = {
                    name: item.name,      // 显示标签名称
                    value: item.value     // 实际值
                };

                // 如果值是负数，为了保证和原样例一致，加上 labelRight
                if (item.value < 0) {
                    valueItem.label = labelRight;
                }

                return valueItem;
            });

            // 构建一个完整的系列配置
            seriesList.push({
                name: groupName,   // 系列名称
                type: 'bar',       // 柱状图
                stack: 'Total',    // 堆叠配置
                label: {
                    show: seriesConfig.showLabels !== false,
                    formatter: '{b}'   // 显示数据项的 name
                },
                itemStyle: {
                    color: params => {
                        // 根据正负值决定颜色
                        return params.value >= 0
                            ? (seriesConfig.positiveColor || '#409eff')
                            : (seriesConfig.negativeColor || '#f56c6c');
                    }
                },
                data: seriesData
            });
        });

        return seriesList; // 返回完整的 series 数组
    }


    // 获取Y轴数据
    getYAxisData() {
        const config = this.getDefaultConfig();
        const yAxisConfig = window.attributeUtils.buildConfig(this, config.yAxisAttrs);
        try {
            return JSON.parse(yAxisConfig.data || '[]');
        } catch (e) {
            return ['ten', 'nine', 'eight', 'seven', 'six', 'five', 'four', 'three', 'two', 'one'];
        }
    }

    // 重写默认数据，确保与样例一致
    getDefaultData() {
        // 数据结构与样例保持一致
        return [
            {
                "Cost": [
                    { "value": -0.07 },
                    { "value": -0.09 },
                    { "value": 0.2 },
                    { "value": 0.44 },
                    { "value": -0.23 },
                    { "value": 0.08 },
                    { "value": -0.17 },
                    { "value": 0.47 },
                    { "value": -0.36 },
                    { "value": 0.18 }
                ]
            }
        ];
    }

    // 重写渲染方法，确保tooltip等配置与样例一致
    renderChart(seriesConfig, titleConfig, gridConfig, xAxisConfig, yAxisConfig, legendConfig, data = null) {
        // 强制使用内部定义的数据以确保与样例一致
        const dataDemo = data || this.getDefaultData();

        // 提示框配置完全匹配样例
        const tooltipConfig = {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        };

        // X轴分割线配置
        xAxisConfig.splitLine = {
            lineStyle: {
                type: 'dashed'
            }
        };

        // 调用父类方法，传递完整配置
        super.renderChart(
            { ...seriesConfig, tooltip: tooltipConfig },
            titleConfig,
            gridConfig,
            xAxisConfig,
            yAxisConfig,
            legendConfig,
            dataDemo
        );
    }

    // 处理属性变化
    handleAttributeChange(name, value, currentOptions) {
        super.handleAttributeChange(name, value, currentOptions);

        if (['negative-color', 'positive-color', 'show-labels'].includes(name)) {
            this.reRenderChart();
        }
    }

    // 重新渲染图表
    reRenderChart() {
        const { buildConfig } = window.attributeUtils;
        const config = this.getDefaultConfig();

        const seriesConfig = buildConfig(this, config.seriesAttrs);
        const titleConfig = buildConfig(this, config.titleAttrs);
        const gridConfig = buildConfig(this, config.gridAttrs);
        const xAxisConfig = buildConfig(this, config.xAxisAttrs);
        const yAxisConfig = buildConfig(this, config.yAxisAttrs);
        const legendConfig = buildConfig(this, config.legendAttrs);

        this.renderChart(seriesConfig, titleConfig, gridConfig, xAxisConfig, yAxisConfig, legendConfig);
    }
}

// 注册自定义元素
customElements.define('bar-chart-with-negative-value', ExactNegativeBarChart);
